package com.hmbe.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmbe.dto.UserDTO;
import io.netty.util.internal.StringUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmbe.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmbe.utils.RedisConstants.LOGIN_USER_TTL;

public class LoginInterceptor implements HandlerInterceptor {
    private StringRedisTemplate redisTemplate;

    public LoginInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*//1.获取sesion域中的用户信息
        Object user = request.getSession().getAttribute("user");
        //2.判断用户是否为空
        if (user == null) {
            //3.不存在,拦截,返回401状态码
            response.setStatus(401);
            return false;
        }
        //4.存在,保存用户信息到ThreadLocal
        UserHolder.saveUser((UserDTO) user);
        return true;*/
        //return next(request,response,handler);

        //hmbe系统的跨域处理
        return hmBeNext(request, response, handler);
    }

    private boolean hmBeNext(HttpServletRequest request, HttpServletResponse response, Object handler) {
        return true;
    }

    private boolean next(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //1.获取请求头中的token
        String token = request.getHeader("authorization");
        if (StringUtil.isNullOrEmpty(token)) {
            //2.如果token不存在,拦截,返回401状态码
            response.setStatus(401);
            return false;
        }
        //3.根据token获取redis中用户信息
        Map<Object, Object> userMap = redisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        //4.判断用户是否存在
        if (userMap.isEmpty()) {
            //5.不存在,拦截,返回401状态码
            response.setStatus(401);
            return false;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), true);
        //6.存在,保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);
        //7.刷新token的过期时间
        redisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
